package com.lccviolet;

import java.util.concurrent.*;

/**
 * @author LiChaochao
 * @Date 2021/9/16 12:48
 * @Description 线程池底层实现类：ThreadPoolExecutor，手动创建一个线程池
 */
public class MyThreadPoolDemo {
    public static void main(String[] args) {
        /*
         * 最多完成maximumPoolSize + 阻塞队列长度个线程任务。
         * 下一个任务就会报异常 RejectedExecutionException
         * */
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                500,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> System.out.println(Thread.currentThread().getName() + "办理"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    private static void executorsCreateThreadPool() {
//        ExecutorService executorService = Executors.newFixedThreadPool(5); 固定线程数量
//        ExecutorService executorService = Executors.newSingleThreadExecutor(); 一个线程数
        ExecutorService executorService = Executors.newCachedThreadPool(); // 可变线程数

        try {
            for (int i = 0; i < 10; i++) {
                executorService.execute(() -> System.out.println(Thread.currentThread().getName() + "办理"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}
